package com.sse.product.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sse.product.rbac.entity.Menus;
import com.sse.product.rbac.entity.User;
import com.sse.product.rbac.mapper.MenusMapper;
import com.sse.product.rbac.mapper.UserMapper;
import com.sse.product.model.rbac.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author HP
 * @since 2024/5/27
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenusMapper menusMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        //如果没有查到，则通过异常返回
        if (Objects.isNull(user)) {
            throw new  RuntimeException("系统提示：用户名或密码错误！");
        }

        //2.查询权限信息
        List<Menus> menus = menusMapper.queryUserAuthority(user.getId());
        List<String> roles = menus.stream().map(function -> function.getName()).collect(Collectors.toList());

        //2.封装成UserDetas对象返回
        return new LoginUser(user, roles);
    }

}
